package com.taotao.controller;

import com.alibaba.fastjson.JSONObject;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.XmlUtil;
import com.taotao.common.wxpay.MyWXConfig;
import com.taotao.common.wxpay.WXPay;
import com.taotao.mapper.EyGoodsMapper;
import com.taotao.mapper.EyOrderMapper;
import com.taotao.mapper.EyServiceMapper;
import com.taotao.pojo.EyOrder;
import com.taotao.pojo.EyOrderExample;
import com.taotao.service.ParamService;
import com.taotao.service.PictureService;
import com.taotao.service.WechatPayService;
import com.taotao.service.WechatService;
import com.taotao.service.impl.ParamServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Controller
public class ApiWechatController {
	private static final Logger logger = LoggerFactory.getLogger(ApiWechatController.class);

	@Autowired
	EyOrderMapper eyOrderMapper;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyServiceMapper eyServiceMapper;
	@Autowired
	WechatPayService wechatPayService;
	@Autowired
	PictureService pictureService;
	@Autowired
	WechatService wechatService;
	@Autowired
	ParamService paramService;

	public static ApiSocketController apiSocketController;
	
	BaseResult baseResult = new BaseResult();

	@RequestMapping(value="/api/wxPayNotify")
	@ResponseBody
    public  void wxPayNotify(HttpServletRequest request,HttpServletResponse response){
		try {
			PrintWriter writer = response.getWriter();
			String noticeStr="";
			Map<String, String> map = XmlUtil.xmlToMap(request);
			System.out.println("收到支付异步通知"+map.toString());
			MyWXConfig.init(ParamServiceImpl.getResourceParam("apiclient_cert_path"));
		    MyWXConfig config = new MyWXConfig();
		    WXPay wxpay = new WXPay(config);
	        if (wxpay.isPayResultNotifySignatureValid(map)) {
	        	//支付完成确认订单提醒
	        	EyOrderExample exampleOrder = new EyOrderExample();
	        	String out_trade_no=map.get("out_trade_no");
				EyOrderExample.Criteria criteriaOrder = exampleOrder.createCriteria();
				criteriaOrder.andOutTradeNoEqualTo(out_trade_no);
				List<EyOrder> orderList = eyOrderMapper.selectByExample(exampleOrder);
				if(orderList!=null  && orderList.size()>0){
					if(apiSocketController==null){
						apiSocketController = SpringContext.getBean(ApiSocketController.class);
					}
					EyOrder eyOrder = orderList.get(0);
					if(Constants.goods.equals(eyOrder.getModeType())){ //goods类 支付完成确认订单提醒
						JSONObject messageJson=wechatPayService.getCheekGoodsMessageJson(eyOrder);
						apiSocketController.sendToUser(messageJson.toJSONString());
					}else if(Constants.service.equals(eyOrder.getModeType())){ //service类 支付完成确认订单提醒
						JSONObject messageJson=wechatPayService.getCheekServiceMessageJson(eyOrder);
						apiSocketController.sendToUser(messageJson.toJSONString());
					}
					System.out.println("签名正确");
					// 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
					Map<String, Object> returnMap = wechatPayService.wxPayNotify(map,eyOrder);
					if("-1".equals(returnMap.get("code"))){
						noticeStr = XmlUtil.toXML("FAIL", "");
					}else{
						noticeStr = XmlUtil.toXML("SUCCESS", "");
					}
				}else{
					noticeStr = XmlUtil.toXML("FAIL", "");
				}
	        }
	        else { 
	        	System.out.println("签名失败");
				noticeStr = XmlUtil.toXML("FAIL", "签名失败");
	        }
	        writer.write(noticeStr);
            writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@RequestMapping(value="/api/getAuthInfo")
	@ResponseBody
    public  void getAuthInfo(HttpServletRequest request){
		try {
		    String code=request.getParameter("code");//公众号授权code
	        String unionid=request.getParameter("unionid");//公众号授权code
	        System.out.println("调用获取授权接口getAuthInfo code:"+code+",unionid:"+unionid);
	        wechatService.getAuthInfo(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	
	
	@RequestMapping(value="/api/acceptPublicMessage")
	@ResponseBody
    public  void acceptPublicMessage(HttpServletRequest request,HttpServletResponse response){
		try {
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String echostr = request.getParameter("echostr");
			
			System.out.println("signature："+signature);
			System.out.println("timestamp："+timestamp);
			System.out.println("nonce："+nonce);
			System.out.println("echostr："+echostr);
			if(StringUtils.isNoneBlank(echostr)){
				PrintWriter out = response.getWriter();
				if(com.taotao.common.utils.CheckSignatureUtil.checkSignature(signature, timestamp, nonce)){
					out.print(echostr);
				} 
				out.close();
		        out = null;
			}else{
				Map<String, String> map = XmlUtil.xmlToMap(request);
				wechatService.acceptPublicMessage(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
}
